/**
* Copyright 2013 nabla
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package com.nabla.wapp.report.client.parameter;

import java.util.logging.Logger;

import com.nabla.wapp.client.general.LoggerFactory;
import com.nabla.wapp.client.ui.form.Form;
import com.nabla.wapp.report.shared.parameter.CascadingParameterGroup;
import com.nabla.wapp.report.shared.parameter.ParameterValueList;
import com.nabla.wapp.shared.slot.ISlot1;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;

public class CascadingParameterGroupBinder extends ParameterGroupBinder {

	private static final long serialVersionUID = 1L;
	private static final Logger	log = LoggerFactory.getLog(CascadingParameterGroupBinder.class);

	public CascadingParameterGroupBinder(final CascadingParameterGroup parameter, final ParameterValueList parameterValues) {
		super(parameter, parameterValues);
	}

	@Override
	public void bind(final Form form, final ISlot1<String> onReadyHandler) {
		super.bind(form, onReadyHandler);

		log.fine("cascading parameter count = " + parameter.size());
        for (int i = 0; i < parameter.size() - 1; ++i) {
        	final Integer index = i;
            form.getItem(parameter.get(i).getName()).addChangedHandler(new ChangedHandler() {
                @Override
				public void onChanged(@SuppressWarnings("unused") ChangedEvent event) {
                	log.fine("value changed for parameter " + parameter.get(index).getName());
                    get(index).storeValue(form);
                    get(index + 1).onPreviousChanged(form);
                }
            });
        }
	}

}
